package com.leyou.auth.service;

import com.leyou.auth.clients.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserInfo;
import com.leyou.user.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;


@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProp;
    private Logger logger = LoggerFactory.getLogger(AuthService.class);

    //登录token授权
    public String authentication(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }
        User user = userClient.queryUser(username, password);
        if (user == null) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        try {
            String ly_token = JwtUtils.generateToken(userInfo, jwtProp.getPrivateKey(), 30);
            return ly_token;
        } catch (Exception e) {
            logger.error("登录授权失败:username:{},获取token异常", username);
            return null;
        }
    }


}
